//
//  RHBatteryClusterChartVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/26.
//

#import "RHBatteryClusterChartVC.h"
#import "RHBatteryClusterFullChartVC.h"
#import "DevChartParamsModel.h"
#import "SYChartTool.h"
#import "DevChartModel.h"
#import "DeviceChartFieldModel.h"
#import "RHBatteryClusterChartCell.h"
#import "RHDevPackModel.h"
#import "RHCellRealDataModel.h"
#import "RHBatteryCellVC.h"

@interface RHBatteryClusterChartVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong)UIView *headerView;
@property (nonatomic, strong) NSArray *headerDataArr;

@property (nonatomic, strong) NSArray *dataArr;

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;
@end

@implementation RHBatteryClusterChartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    
    [self createData];
    [self getMasterData];
    [self getPackInfoWithMaster:self.masterSN];
    [self setupUI];
}


-(void)createData
{
    NSArray *sectionTitles = @[@"电压统计".rh_localized,@"温度统计".rh_localized];
    NSArray *subTitleArr = @[@"单体电池电压实时曲线".rh_localized,@"单体电池温度实时曲线".rh_localized];
    NSArray *unitArr = @[[NSString stringWithFormat:@"%@(mV)",@"电压".rh_localized],[NSString stringWithFormat:@"%@(℃)",@"温度".rh_localized]];
    NSMutableArray *tempArr = [NSMutableArray array];
    [sectionTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHCellRealDataModel *model = [[RHCellRealDataModel alloc]init];
        model.sectionTitle = sectionTitles[idx];
        model.title = subTitleArr[idx];
        model.unit = unitArr[idx];
        [tempArr addObject:model];
    }];
    self.dataArr = tempArr.copy;
}


-(void)setupUI
{
    kWeakSelf;
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = self.headerView;
    [_tableView registerClass:[RHBatteryClusterChartCell class] forCellReuseIdentifier:@"RHBatteryClusterChartCell"];
//    [_tableView registerClass:[RHStringDataCell class] forCellReuseIdentifier:@"RHStringDataCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getMasterData];
        [weakSelf getPackInfoWithMaster:weakSelf.masterSN];
    }];
}

#pragma mark ------- network -----
-(void)getMasterData
{
    [QMUITips showLoadingInView:self.view];
    NSArray *masterParas = @[@"Mtr_TV",
                             @"Mtr_Cur",
                             @"Mtr_SOC",
                             @"Mtr_SOH"
    ];
    
    NSDictionary *para = @{@"deviceId":ValidNullData(self.devModel.deviceId),
                           @"endpointTypeCode":@"Master",
                           @"keyCodes":masterParas,
                           @"endpointSn":ValidNullData(self.masterSN)
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                [self updateMasterData:request.responseObject[@"data"]];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

#pragma mark ----- 根据master获取 pack和电芯数据
-(void)getPackInfoWithMaster:(NSString*)masterSN
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"deviceId":ValidNullData(self.devModel.deviceId),
                           @"masterSn":ValidNullData(masterSN)};
    [RHDevPackModel startGetWithCompletionAPIKey:H_getPackCellData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
          
            NSArray *arr = resultModel.data;
            //电压数据
            NSMutableArray *vArray = [NSMutableArray array];
            //温度数据
            NSMutableArray *tArray = [NSMutableArray array];
            
            
            [arr enumerateObjectsUsingBlock:^(RHDevPackModel  *_Nonnull packModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [packModel.volt enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [vArray addObject:ValidNullDataToString(obj, @"0")];
                }];
                [packModel.temp enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [tArray addObject:ValidNullDataToString(obj, @"0")];
                }];
                
                
//
            }];
            
            NSMutableArray *xValues = [NSMutableArray array];
            for (int i = 0; i < vArray.count; i++) {
                [xValues addObject:[NSString stringWithFormat:@"%d",i]];
            }
            
            
            RHCellRealDataModel *voltModel = [self.dataArr firstObject];
            voltModel.packArr = arr;
            voltModel.yValues = vArray;
            voltModel.color = @"8956F8";
            voltModel.xValues = xValues.copy;
            
            RHCellRealDataModel *tempModel = [self.dataArr lastObject];
            tempModel.packArr = arr;
            tempModel.yValues = tArray;
            tempModel.color = @"FDD015";
            tempModel.xValues = xValues.copy;
            
            if (vArray.count == 0) {
                voltModel.yValues = @[@(0)];
                voltModel.xValues = @[@""];
                voltModel.maxValue = 100;
                
                tempModel.yValues = @[@(0)];
                tempModel.xValues = @[@""];
                tempModel.maxValue = 100;
            }
           
        }
        [self.tableView reloadData];
        [self.tableView endHeaderRefresh];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
        
}

-(void)updateMasterData:(NSDictionary*)dic
{
    kWeakSelf;
    NSArray *dataKeys = @[@"Mtr_SOC",@"Mtr_SOH",@"Mtr_TV",@"Mtr_Cur"];
    [self.headerDataArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUILabel *lab = [weakSelf.headerView viewWithTag:100+idx];
        NSString *key = dataKeys[idx];
        lab.text = [NSString stringWithFormat:@"%@%@",ValidNullDataToString(dic[key], @"--"),dic[CellUint]];
    }];
}

#pragma mark ------- action -----
-(void)fullAction:(NSInteger)section
{
    RHBatteryClusterFullChartVC *fullVC = [[RHBatteryClusterFullChartVC alloc]initWithModel:self.dataArr[section] ];
    [self.navigationController pushViewController:fullVC animated:NO];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = kView;
    RHCellRealDataModel *model = self.dataArr[section];
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(15);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = model.sectionTitle;
    [headView addSubview:titleLab];
    
    QMUIButton *fullBtn = [[QMUIButton alloc]init];
    [fullBtn setImage:[UIImage imageNamed:@"arrow"] forState:UIControlStateNormal];
    [headView addSubview:fullBtn];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).offset(15);
        make.bottom.mas_offset(-10);
     }];
    
    [fullBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset (-15);
        make.width.height.offset(35);
        make.centerY.equalTo(titleLab);
    }];
    
    kWeakSelf;
    [[fullBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf fullAction:section];
    }];
    
   return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    RHBatteryClusterChartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHBatteryClusterChartCell"];
    cell.chartModel = self.dataArr[indexPath.section];
    kWeakSelf;
    cell.fullChartBlock = ^{
        [weakSelf fullAction:indexPath.section];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}


-(UIView *)headerView
{
    if(!_headerView){
        self.headerDataArr = @[@{CellTitle:@"SOC",CellIcon:@"dev_cell_soc",CellUint:@"(%)"},
                                @{CellTitle:@"SOH",CellIcon:@"dev_cell_soh",CellUint:@""},
                                @{CellTitle:@"电压".rh_localized,CellIcon:@"dev_cell_vol",CellUint:@"(V)"},
                                @{CellTitle:@"电流".rh_localized,CellIcon:@"dev_cell_ele",CellUint:@"(A)"}
                                ];
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 64*2+35)];
        _headerView.backgroundColor = CFTabViewBgColor;
        
        __block UIView *lastView;
        __block CGFloat itemWidth = (kUI_WINDOW_W - 45)/2;
        [self.headerDataArr enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
            UIView *itemView = [self itemViewWithTitle:dic[CellTitle] icon:dic[CellIcon] index:idx];
            [_headerView addSubview:itemView];
            if(idx == 0){
                [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.top.mas_offset(15);
                    make.width.offset(itemWidth);
                    make.height.offset(64);
                }];
            }else{
                if(idx%2==0){
                    [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.mas_offset(15);
                        make.size.equalTo(lastView);
                        make.top.equalTo(lastView.mas_bottom).offset(15);
                    }];
                }else{
                    [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(lastView.mas_right).offset(15);
                        make.size.top.equalTo(lastView);
                    }];
                }
            }
            lastView = itemView;
        }];
    }
    return _headerView;
}

-(UIView*)itemViewWithTitle:(NSString*)title icon:(NSString*)icon index:(NSInteger)index;
{
    UIView *bgView = kView;
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:icon]];
    [bgView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(25));
        make.left.top.mas_offset(15);
    }];
    
   QMUILabel* contentLab = [[QMUILabel alloc]init];
    contentLab.text = @"--";
    contentLab.font = [UIFont boldSystemFontOfSize:16];
    contentLab.textAlignment = NSTextAlignmentLeft;
    contentLab.textColor = kCOLOR_HEX(@"3F4443");
    contentLab.tag = 100 + index;
    [bgView addSubview:contentLab];
    
    QMUILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.text = title;
    titleLab.font = [UIFont systemFontOfSize:13];
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.textColor = kCOLOR_HEX(@"3F4443");
    [bgView addSubview:titleLab];
    
    kWeakSelf;
    [contentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.mas_right).offset(kScaleW(15));
        make.top.mas_offset(15);
        make.right.mas_offset(-15);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentLab);
        make.top.equalTo(contentLab.mas_bottom).offset(5);
        make.right.mas_offset(-15);
    }];
    
    return bgView;
}



#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}
@end
